# app.py
from flask import Flask, render_template, jsonify, send_from_directory
import os
from threading import Timer
import webbrowser

app = Flask(__name__)


# 获取photos目录下的所有图片文件
def get_images_from_folder():
    photos_dir = os.path.join(os.path.dirname(__file__), 'photos')
    images = []

    if os.path.exists(photos_dir):
        valid_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')
        for filename in os.listdir(photos_dir):
            if filename.lower().endswith(valid_extensions):
                images.append({
                    'filename': filename,
                    'title': os.path.splitext(filename)[0].replace('_', ' ').title(),
                    'description': '我们的美好回忆'
                })

    # 如果没有图片，返回默认示例
    if not images:
        images = [
            {'filename': 'sample1.jpg', 'title': '星空下的约定', 'description': '与你一起仰望星空的夜晚'},
            {'filename': 'sample2.jpg', 'title': '海边漫步', 'description': '海风轻抚，与你同行'},
            {'filename': 'sample3.jpg', 'title': '花海徜徉', 'description': '在花海中寻找你的身影'}
        ]

    return images


@app.route('/')
def index():
    return render_template('langman.html')


@app.route('/api/images')
def get_images():
    images = get_images_from_folder()
    return jsonify(images)


# 添加图片路由，允许访问photos文件夹中的图片
@app.route('/photos/<path:filename>')
def serve_photo(filename):
    photos_dir = os.path.join(os.path.dirname(__file__), 'photos')
    return send_from_directory(photos_dir, filename)

def open_browser():
    """在浏览器中打开应用"""
    webbrowser.open_new('http://localhost:5000')
if __name__ == '__main__':
    Timer(3, open_browser).start()
    app.run(debug=True)